//
//  MainTableViewController.m
//  GiftItems
//
//  Created by lanou3g on 15/9/18.
//  Copyright (c) 2015年 lanou3g. All rights reserved.
//

#import "MainTableViewController.h"
#import "MainBoutiqueModel.h"
#import "MainTableViewCell.h"
#import "MainHeaderView.h"

#import "MoreSpecialTableViewController.h"
#import "SpecialDetailsTableViewController.h"

#import "SearchViewController.h"
#import "SweepViewController.h"
@interface MainTableViewController ()<UIScrollViewDelegate>
@property (nonatomic,strong)NSMutableArray *selectImageArray;
@property (nonatomic,strong) NSMutableArray *collectionsArray;
@property (nonatomic,strong) MainHeaderView *headerView;
@property (nonatomic,strong)NSString *NextUrl;
@property (nonatomic,strong)UIPageControl *pageControl;

@property (nonatomic,strong)UIButton *toTopbutton;

@end

@implementation MainTableViewController

- (void)viewDidLoad {
    [super viewDidLoad];
   
    
    [self reloadSetData:KSelectionUrl];
    [self reloadBanner];
    
    //注册cell
    [self.tableView registerClass:[MainTableViewCell class] forCellReuseIdentifier:@"cell"];
    // 添加刷新
    [self refresh];
    // 添加加载动画
    [self loadAnimation];
    // 添加二维码扫描按钮
    [self addSweepButton];
    
    // 取消tableView 线
    self.tableView.separatorStyle = NO;
   //添加搜索按钮
    [self addSeachButton];
    // 添加跳转顶部按钮
    [self addToTopButton];
}
//添加上拉加载 下拉刷新
- (void)refresh {

    //上拉加载
    __block MainTableViewController *weakSelf = self;
    [self.tableView addRefreshWithRefreshViewType:(LORefreshViewTypeFooterDefault) refreshingBlock:^{
        
        [weakSelf reloadSetData:weakSelf.NextUrl];
        [weakSelf.tableView.defaultFooter endRefreshing];
    }];
    //下拉刷新
    [self.tableView addRefreshWithRefreshViewType:(LORefreshViewTypeHeaderDefault) refreshingBlock:^{
        weakSelf.selectImageArray = nil;
        [weakSelf reloadSetData:KSelectionUrl];
        // [weakSelf startBtn];
        [weakSelf.tableView reloadData];
        [weakSelf.tableView.defaultHeader endRefreshing];
    }];
}


// 回到最顶部
- (void)addToTopButton {
    self.toTopbutton = [UIButton buttonWithType:(UIButtonTypeCustom)];
    self.toTopbutton.frame = CGRectMake(kWidth - 60, kHeight - 200, 40, 40);
    [self.toTopbutton setImage:[UIImage imageNamed:@"Entypo_e4af(0)_256"] forState:(UIControlStateNormal)];
    [self.toTopbutton addTarget:self action:@selector(toTop) forControlEvents:(UIControlEventTouchUpInside)];
    self.toTopbutton.alpha = 0;
    [self.view addSubview:self.toTopbutton];
}
- (void)toTop {
    
    self.tableView.contentOffset = CGPointMake(0, 0);
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    self.toTopbutton.alpha = self.tableView.contentOffset.y / 1000.0;
    self.toTopbutton.frame = CGRectMake(kWidth - 60, kHeight- 200 + self.tableView.contentOffset.y, 40, 40);
}

//添加二维码扫描按钮
- (void)addSweepButton {
    //设置二维码扫一扫按钮
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"icon_homepage_scan_pressed@2x.png"] style:UIBarButtonItemStylePlain target:self action:@selector(actionButton:)];
    self.navigationItem.leftBarButtonItem = leftButton;
}

// 跳转扫描二维码界面
- (void)actionButton:(UIBarButtonItem *)button{
    SweepViewController *sweep = [[SweepViewController alloc] init];
    [self.navigationController pushViewController:sweep animated:YES];
}

//添加搜索按钮
- (void)addSeachButton {
    // 设置搜索按钮
    UIBarButtonItem *rigntButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemSearch) target:self action:@selector(searchVC)];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.navigationItem.rightBarButtonItem = rigntButton;
}
// 跳转搜索界面
- (void)searchVC {
    
    SearchViewController *searchVC = [[SearchViewController alloc] init];
    
    [self presentViewController:searchVC animated:YES completion:nil];
    
}

#pragma mark --- 加载动画 ---

- (void)loadAnimation {
    
    //添加加载动画
    indicator = [[YYAnimationIndicator alloc] initWithFrame:CGRectMake(self.view.frame.size.width/2-40, self.view.frame.size.height/2-40, 80, 80)];
    [indicator setLoadText:@"正在加载..."];
    [self.view addSubview:indicator];
    [self startBtn];
}

- (void)startBtn {
    // 开始转动
    [indicator startAnimation];
}

/*
 当Type为YES时消失  NO时不消失
 */
-(void)StopBtn
{
    [indicator stopAnimationWithLoadText:@"finish" withType:YES];//加载成功
}

-(void)StopFailBtn
{
    [indicator stopAnimationWithLoadText:@"加载失败" withType:NO];//加载失败
}


#pragma mark --- 轮播图 ---
//轮播图
- (void)MainHeaderView {
    
    
    self.headerView = [[MainHeaderView alloc] initWithFrame:CGRectMake(0, 0, kWidth, 170)imageArray:self.collectionsArray delegate:self action:@selector(touchImage) timer:3.0 selector:@selector(circulary)];
    self.headerView.delegate = self;
    
    self.pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(30,self.headerView.frame.size.height - 30, 80, 30)];
    self.pageControl.numberOfPages = self.collectionsArray.count;
    self.pageControl.backgroundColor = [UIColor clearColor];
    [self.tableView addSubview:self.pageControl];
    
    self.headerView.showsHorizontalScrollIndicator = NO;
    self.tableView.tableHeaderView = self.headerView;
    
    
}
//点击轮播图触发事件
- (void)touchImage {
    
   NSInteger index = self.headerView.contentOffset.x / kWidth;
    
    MainBoutiqueModel *model = [[MainBoutiqueModel alloc] init];
    
    if (index == 0) {
        model = [self.collectionsArray lastObject];
    }if (index == self.collectionsArray.count + 1) {
        model = [self.collectionsArray firstObject];
    }else {
        model = self.collectionsArray[index - 1];
    }
    
    
    SpecialDetailsTableViewController *specialVC = [[SpecialDetailsTableViewController alloc] init];
    NSString *newUrl = [KRotateDetailsUrl stringByReplacingOccurrencesOfString:@"参数" withString:[NSString stringWithFormat:@"%@",model.ID]];
    specialVC.specialDeatilsUrl = newUrl;
    [self.navigationController pushViewController:specialVC animated:YES];

    NSLog(@"%ld",(long)index);
    
}
// 封装循环滚动方法在手动滑动与定时器方法内调用
- (void)scrollViewDidCircularly {
    if (self.headerView.contentOffset.x == 0) {
        [self.headerView setContentOffset:CGPointMake((self.collectionsArray.count ) * kWidth, 0) animated:NO];
    }
    else if (self.headerView.contentOffset.x == (self.collectionsArray.count + 1) * kWidth) {
        [self.headerView setContentOffset:CGPointMake(self.headerView.bounds.size.width, 0) animated:NO];
    }
    
    
}

// 结束减速时触发
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self scrollViewDidCircularly];
    
    [self pageContorlNumb];
    
    
}
// 定时器设置循环滚动
- (void)circulary {
    
    [self scrollViewDidCircularly];
    CGPoint newpoint = self.headerView.contentOffset;
    
    [self pageContorlNumb];
    
    newpoint.x += kWidth;
    [self.headerView setContentOffset:newpoint animated:YES];
    
}

//pageControl Number
- (void)pageContorlNumb {
    
    NSInteger pageNum = self.headerView.contentOffset.x / kWidth;
    
    if (self.headerView.contentOffset.x / kWidth == 5) {
        self.pageControl.currentPage = 0;
    }else {
        self.pageControl.currentPage = pageNum;
    }

    
    
}

//轮播图上更多按钮
- (void)moreButton {
    
    UIButton *moreButton = [UIButton buttonWithType:UIButtonTypeCustom];
    moreButton.frame = CGRectMake(kWidth - 90, 135, 80, 30);
    [moreButton setTitle:@"全部专题" forState:(UIControlStateNormal)];

    [moreButton setTintColor:[UIColor clearColor]];
    [moreButton setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.2]];

    moreButton.layer.masksToBounds = YES;
    moreButton.layer.cornerRadius = 15;
    [self.tableView addSubview:moreButton];
    
    [moreButton addTarget:self action:@selector(moreButtonClick:) forControlEvents:(UIControlEventTouchUpInside)];
}
// 跳转更多专题
- (void)moreButtonClick:(UIButton *)button {
    
    MoreSpecialTableViewController *moreSpecial = [[MoreSpecialTableViewController alloc] init];
    [self.navigationController pushViewController:moreSpecial animated:YES];
    
    
}

#pragma mark --- 数据解析 ---
// 精选图片解析
- (void)reloadSetData:(NSString *)url {
    
    [LORequestManger GET:url success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        NSDictionary *dicData = dic[@"data"];
        NSDictionary *dicPaging = dicData[@"paging"];
        self.NextUrl = dicPaging[@"next_url"];
        for (NSDictionary *items in dicData[@"items"]) {
            MainBoutiqueModel *model = [MainBoutiqueModel shareDictionary:items];
            [self.selectImageArray addObject:model];
        }
        [self.tableView reloadData];
        [self StopBtn];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}
// 精选图片数组懒加载
- (NSMutableArray *)selectImageArray {
    
    if (!_selectImageArray) {
        _selectImageArray = [[NSMutableArray alloc] init];
    }
    return _selectImageArray;
    
}

//轮播图解析
- (void)reloadBanner {
    [LORequestManger GET:KRotateWUrl success:^(id response) {
        NSDictionary *dic = (NSDictionary *)response;
        NSDictionary *dicData = dic[@"data"];
        for (NSDictionary *collections in dicData[@"collections"]) {
            MainBoutiqueModel *model = [MainBoutiqueModel shareDictionary:collections];
            [self.collectionsArray addObject:model];
        }
        [self MainHeaderView];
        [self moreButton];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (NSMutableArray *)collectionsArray {
    
    if (!_collectionsArray) {
        _collectionsArray = [[NSMutableArray alloc] init];
    }
    return _collectionsArray;
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    return self.selectImageArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MainTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
    if (cell== nil) {
        cell = [[MainTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"cell"];
    }
    cell.LickCountButton.tag = indexPath.row;
    [cell.LickCountButton addTarget:self action:@selector(clickZan:) forControlEvents:(UIControlEventTouchUpInside)];
    
    
    
    
    MainBoutiqueModel *model = self.selectImageArray[indexPath.row];
    
    
    NSArray *modelArray = [[StrategyDataBase shareDataBase] findStrategyModelByTitle:model.title];
    MainBoutiqueModel *modelTitle = modelArray.lastObject;
    
    if (modelTitle) {
        [cell.LickCountButton setImage:[UIImage imageNamed:@"profile_btn_like"] forState:UIControlStateNormal];
    }else {
        [cell.LickCountButton setImage:[UIImage imageNamed:@"profile_btn_unlike"] forState:UIControlStateNormal];
        
    }
    
    [cell shareMainImageModel:model];
    
    return cell;
}

// 点赞
- (void)clickZan:(UIButton *)button {
   
    MainBoutiqueModel *model = self.selectImageArray[button.tag];

    CAKeyframeAnimation *k = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    k.values = @[@(0.1),@(1.0),@(1.5)];
    k.keyTimes = @[@(0.0),@(0.5),@(0.8),@(1.0)];
    k.calculationMode = kCAAnimationLinear;
    
    NSArray *modelArray = [[StrategyDataBase shareDataBase] findStrategyModelByTitle:model.title];
    MainBoutiqueModel *modelTitle = modelArray.lastObject;
    
    if (!modelTitle) {
        [button setImage:[UIImage imageNamed:@"profile_btn_like"] forState:UIControlStateNormal];
        button.tintColor = [UIColor redColor];
        [[StrategyDataBase shareDataBase] createStrategyListWithName:@"strategyList"];
        [[StrategyDataBase shareDataBase] insertModel:model];
        [[StrategyDataBase shareDataBase] showAlert];
        NSUInteger linkCount = [model.likes_count integerValue] + 1;
        [button setTitle:[NSString stringWithFormat:@"%lu",(unsigned long)linkCount] forState:(UIControlStateNormal)];
        
        
    }else
    {
        [button setImage:[UIImage imageNamed:@"profile_btn_unlike"] forState:UIControlStateNormal];
        button.tintColor = [UIColor whiteColor];
        [[StrategyDataBase shareDataBase] createStrategyListWithName:@"strategyList"];
        [[StrategyDataBase shareDataBase] deleteModelWithStrategy:model.title];
        [[StrategyDataBase shareDataBase] deleteAlert];

        [button setTitle:[NSString stringWithFormat:@"%@",model.likes_count] forState:(UIControlStateNormal)];
        
    }
    [button.layer addAnimation:k forKey:@"SHOW"];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 160;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    WebViewController *webView = [[WebViewController alloc] init];
    
    MainBoutiqueModel *model = [[MainBoutiqueModel alloc] init];
    
    model = self.selectImageArray[indexPath.row];
    
    webView.webUrl = [KStrategyUrl stringByReplacingOccurrencesOfString:@"参数" withString:[NSString stringWithFormat:@"%@",model.ID]];
    NSLog(@"&*&*%@",webView.webUrl);
    webView.type = @"攻略";
    
    [self presentViewController:webView animated:YES completion:nil];
    
    
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
